import {request} from "@umijs/max";
import {message} from "antd";

export async function dictList(key: string) {
  return globalApi('/config/dict', {key})
}

export async function globalApi(path: string, data: any, options?: { [key: string]: any }) {
  return request<Record<string, any>>(`/bdq-admin-api${path}`, {
    method: 'POST',
    data,
    ...(options || {}),
  });
}

export async function globalLoadTableApiCode(path: string, code: string, access: any, param: any, options?: {
  [key: string]: any
}) {
  // const access = useAccess()
  if (!access.canAuth(code)) {
    message.error(`无权限 ${code}`)
    return {success: true, data: [], total: 0}
  }
  return globalLoadTableApi(path, param, options)
}

export async function globalLoadTableApi(path: string, param: any, options?: { [key: string]: any }) {
  console.log('param = ', param)
  const hide = message.loading('正在加载表格')
  const r = await globalApi(path, param, options)
  console.log('r = ', r)
  hide()
  message.success('Loading successfully');
  return {success: r.success, data: r.data.data, total: r.data.total}
}

export const handleGloblApiResult = async (path: string, fields: any) => {
  const hide = message.loading('正在操作');
  try {
    const r = await globalApi(path, {...fields});
    hide();
    message.success('Operation successfully');
    return r;
  } catch (error) {
    hide();
    message.error('Operation failed, please try again!');
    return {};
  }
};

export const handleGloblApi = async (path: string, fields: any) => {
  const hide = message.loading('正在操作');
  try {
    await globalApi(path, {...fields});
    hide();
    message.success('Operation successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Operation failed, please try again!');
    return false;
  }
};
